<?php

/**
 * 数据库公共操作类
 *
 */
class DbModel {

    private $db_type = 'mysql';
    public $db;

    function __construct($db_type) {
        $this->db_type = $db_type;

        try {
            $this->db = DbManager::getInstance($this->db_type);
        } catch (Exception $e) {
            $this->db = null;
            throw new Exception("dbmodel construct Error" . $e->getMessage());
        }
    }

    /**
     * 数据库表查询
     * @param string $sql
     * @return resultSet $rs
     */
    public function query($sql) {
        if ($this->db == null) {
            return false;
        }
        try {
            
            return $this->db->query($sql);
            file_put_contents('a.txt', $db->errorInfo());
            //file_put_contents('a.txt', $db->errorCode());
        } catch (PDOExecption $e) {
            echo $e;
        }

        return false;
    }

    /**
     * 查询单条记录
     * @param string $sql
     * @return array $data
     */
    public function find($sql) {
        $data = array();
        if ($this->db == null) {
            return false;
        }
        try {
            $rs = $this->query($sql);
            if ($rs) {
                $data = $rs->fetch(PDO::FETCH_ASSOC);
            }
        } catch (PDOExecption $e) {
            throw new Exception("dbmodel find Error" . $e->getMessage());
        }

        return $data;
    }

    /**
     * 查询所有记录
     * @param string $sql
     * @return array $data
     */
    public function findAll($sql) {

        $data = array();
        if ($this->db == null) {
            return false;
        }
        try {
            $rs = $this->query($sql);

            return $rs->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOExecption $e) {
            throw new Exception("dbmodel findAll Error" . $e->getMessage());
        }
    }

    /**
     * 执行SQL
     * @param string $sql
     */
    public function execute($sql) {
        if ($this->db == NULL) {
            return FALSE;
        }

        try {
            return $this->db->exec($sql);
        } catch (PDOExecption $e) {
            throw new Exception("dbmodel execute Error" . $e->getMessage());
        }
    }

    /*
     * return lastinsertid
     */

    public function returnlastinsertid() {
        return $this->db->lastinsertid();
    }

}

?>